import {
  createSlice,
  createAsyncThunk,
  type PayloadAction,
} from "@reduxjs/toolkit";

interface IFilm {
  id: string;
  name: string;
}

export const filmFetchData = createAsyncThunk("film/fetchData", async () => {
  const resp = await fetch("http://localhost:3000/films").then((response) =>
    response.json()
  );
  return resp;
});

const filmSlice = createSlice({
  name: "film",

  initialState: {
    items: [] as IFilm[],
  },

  reducers: {
    addFilm(state, { payload }: PayloadAction<IFilm>) {
      state.items.push(payload);
    },

    delFilm(state, { payload: id }: PayloadAction<string>) {
      state.items = state.items.filter((item) => item.id !== id);
    },

    // ...
  },

  extraReducers: (builder) =>
    builder.addCase(filmFetchData.fulfilled, (state, { payload }) => {
      state.items = payload;
    }),
});

export const { addFilm, delFilm } = filmSlice.actions;

// addFilm() => { type: 'film/addFilm', payload: undefined }
// delFilm() => { type: 'film/delFilm', payload: undefined }

export default filmSlice.reducer;
